package com.deer.wms.ASN.manage.web;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.deer.wms.ASN.manage.constant.AsnManageConstant;
import com.deer.wms.ASN.manage.model.*;
import com.deer.wms.ASN.manage.model.asn.*;
import com.deer.wms.ASN.manage.model.asn.CreateASN.*;
import com.deer.wms.ASN.manage.model.file.FileData;
import com.deer.wms.ASN.manage.model.in.*;
import com.deer.wms.ASN.manage.service.*;
import com.deer.wms.base.system.model.Item.ItemInfo;
import com.deer.wms.base.system.model.Pack.PackDetail;
import com.deer.wms.base.system.model.Supplier.SupplierManage;
import com.deer.wms.base.system.model.erp.ErpInConstant;
import com.deer.wms.base.system.model.erp.ErpOutConstant;
import com.deer.wms.base.system.service.ItemInfoService;
import com.deer.wms.base.system.service.PackDetailService;
import com.deer.wms.base.system.service.SupplierManageService;
import com.deer.wms.intercept.annotation.Authority;
import com.deer.wms.intercept.annotation.User;
import com.deer.wms.intercept.common.data.CurrentUser;
import com.deer.wms.inventory.service.InventoryService;
import com.deer.wms.inventory.service.InventoryTransactService;
import com.deer.wms.lzb.erp.service.ErpRecordService;
import com.deer.wms.project.root.core.result.CommonCode;
import com.deer.wms.project.root.core.result.Result;
import com.deer.wms.project.root.core.result.ResultGenerator;
import com.deer.wms.project.root.exception.ServiceException;
import com.deer.wms.project.root.util.*;
import com.deer.wms.review.manage.model.BillRecord;
import com.deer.wms.review.manage.service.BillRecordService;
import com.deer.wms.review.manage.service.CaseMasterService;
import com.deer.wms.system.manage.constant.SystemManageConstant;
import com.deer.wms.system.manage.model.carrier.Carrier;
import com.deer.wms.system.manage.model.organization.Organization;
import com.deer.wms.system.manage.model.user.UserInfo;
import com.deer.wms.system.manage.model.ware.WareInfo;
import com.deer.wms.system.manage.service.*;
import com.deer.wms.ware.task.constant.WareTaskConstant;
import com.deer.wms.ware.task.model.AllocatingOutboundVo;
import com.deer.wms.ware.task.model.LinesVo;
import com.deer.wms.ware.task.model.SO.SoDetail;
import com.deer.wms.ware.task.model.SO.SoExcelData;
import com.deer.wms.ware.task.model.SO.SoImport;
import com.deer.wms.ware.task.model.SO.SoMaster;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;
import java.util.stream.Collectors;

/**
* Created by guo on 2020/01/03.
*/
@Api(description = "ASN信息api接口")
@RestController
@RequestMapping("/asn/masters")
public class AsnMasterController {

    @Autowired
    private AsnMasterService asnMasterService;
    @Autowired
    private AsnDetailService asnDetailService;
    @Autowired
    private CaseMasterService caseMasterService;
    @Autowired
    private ValidatorService validatorService;
    @Autowired
    private WareInfoService wareInfoService;
    @Autowired
    private OrganizationService organizationService;
    @Autowired
    private SupplierManageService supplierManageService;
    @Autowired
    private CarrierService carrierService;
    @Autowired
    private AsnDetailViewService asnDetailViewService;
    @Autowired
    private ItemInfoService itemInfoService;
    @Autowired
    private PackDetailService packDetailService;
    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private BillRecordService billRecordService;
    @Autowired
    private AcceptExService acceptExService;
    @Autowired
    private AcceptRecordService acceptRecordService;
    @Autowired
    private AsnShipDetailService asnShipDetailService;
    private Result result;

    @ApiOperation(value = "ERP--》WMS生成入库单", notes = "ERP--》WMS生成入库单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "access-token", value = "token", paramType = "header", dataType = "String", dataTypeClass = String.class,  required = true)
    })
    @PostMapping("/createASN")
    public Result createASN(@RequestBody CreateASN createASN, @ApiIgnore @User CurrentUser currentUser) {
        if(currentUser == null){
            return ResultGenerator.genFailResult(CommonCode.MISSING_PERMISSION_PARAMTER, null);
        }
        String wareCode = createASN.getWareCode();
        String orgCode = createASN.getOrgCode();
        AsnMaster asnMaster = asnMasterService.findBy("bill_no",createASN.getBillNo());
        if(asnMaster!=null){
            return ResultGenerator.genFailResult(CommonCode.BILL_NO, null);
        }
        if(wareCode==null){
            return ResultGenerator.genFailResult(CommonCode.WARE_NULL, null);
        }
        if(orgCode==null){
            return ResultGenerator.genFailResult(CommonCode.ORG_NULL, null);
        }

//        if(createASN.getShipList()!=null){
//            for (CreateASNShipDetail createASNShipDetail:createASN.getShipList()
//            ) {
//                AsnShipDetail asnShipDetail = asnShipDetailService.findBy("ship_bill_code",createASNShipDetail.getShipBillCode());
//                if(asnShipDetail!=null){
//                    return ResultGenerator.genFailResult(CommonCode.SHIP_CODE);
//                }
//            }
//        }
        List<CreateASNSKUDetail> asnskuDetails = createASN.getSkuList();
        for(int i = 0;i<asnskuDetails.size();i++){
            CreateASNSKUDetail  createASNSKUDetail = asnskuDetails.get(i);
            ItemInfo itemInfo = itemInfoService.findBy("item_code",createASNSKUDetail.getSkuCode());
            if(itemInfo!=null   && createASNSKUDetail.getSkuName()!=null && !createASNSKUDetail.getSkuName().equals("") ){
                itemInfo.setItemName(createASNSKUDetail.getSkuName());

            }
            if(itemInfo!=null   && createASNSKUDetail.getImgUrl()!=null && !createASNSKUDetail.getImgUrl().equals("") ){

                itemInfo.setImgUrl(createASNSKUDetail.getImgUrl());
            }
        }
        asnMasterService.createASN(createASN,currentUser);
        return ResultGenerator.genSuccessResult();
    }

    @ApiOperation(value = "ERP--》WMS推送入库快递单号", notes = "WMS推送入库快递单号")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "access-token", value = "token", paramType = "header", dataType = "String", dataTypeClass = String.class,  required = true)
    })
    @PostMapping("/addInShipNo")
    public Result addInShipNo(@RequestBody AddInShipNo addInShipNo, @ApiIgnore @User CurrentUser currentUser) {

        if(currentUser == null){
            return ResultGenerator.genFailResult(CommonCode.MISSING_PERMISSION_PARAMTER, null);
        }
        AsnShipDetail asnShipDetail =asnShipDetailService.findBy("ship_bill_code",addInShipNo.getShipBillNo());
        if(asnShipDetail==null){
            asnShipDetail = new AsnShipDetail();
            asnShipDetail.setBillNo(addInShipNo.getBillNo());
            asnShipDetail.setShipBillCode(addInShipNo.getShipBillNo());
            asnShipDetail.setShipCode(addInShipNo.getShipCode());
            asnShipDetailService.save(asnShipDetail);
        }
        return ResultGenerator.genSuccessResult();
    }

    @ApiOperation(value = "ERP--》WMS修改数量", notes = "WMS修改数量")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "access-token", value = "token", paramType = "header", dataType = "String", dataTypeClass = String.class,  required = true)
    })
    @PostMapping("/updateSkuQuantity")
    public Result updateSkuQuantity(@RequestBody UpdateSkuQuantity updateSkuQuantity, @ApiIgnore @User CurrentUser currentUser) {

        if(currentUser == null){
            return ResultGenerator.genFailResult(CommonCode.MISSING_PERMISSION_PARAMTER, null);
        }
        AsnMaster asnMaster = asnMasterService.findSoByBillNo(updateSkuQuantity.getBillNo(),updateSkuQuantity.getWareCode());
        if(asnMaster==null){
            throw new ServiceException(CommonCode.SERVER_INERNAL_ERROR,"单号无效！");
        }
        if(!asnMaster.getWareCode().equals(updateSkuQuantity.getWareCode())){
            throw new ServiceException(CommonCode.SERVER_INERNAL_ERROR,"仓库编码异常："+asnMaster.getWareCode()+"||"+updateSkuQuantity.getWareCode());
        }
        if(updateSkuQuantity.getBillNo()==null||updateSkuQuantity.getBillNo().equals("") ){
            throw new ServiceException(CommonCode.SERVER_INERNAL_ERROR,"没有传单号！");
        }
        List<Sku> skuList = updateSkuQuantity.getSkuList();
        for (Sku sku:skuList  ) {
            if(sku.getQuantity()==null||sku.getQuantity()<0){
                throw new ServiceException(CommonCode.SERVER_INERNAL_ERROR,"数量必须大于0！");
            }
        }

        AcceptExCriteria acceptExCriteria = new AcceptExCriteria();
        acceptExCriteria.setBillNo(updateSkuQuantity.getBillNo());
        List<AcceptExDto> acceptExs = acceptExService.findList(acceptExCriteria);
        if(acceptExs.size()>0){
            throw new ServiceException(CommonCode.SERVER_INERNAL_ERROR,"该入库单已经有验收异常记录！" );
        }
        AcceptRecordCriteria acceptRecordCriteria = new AcceptRecordCriteria();
        acceptRecordCriteria.setAsnBillNo(updateSkuQuantity.getBillNo());
        List<AcceptRecord> acceptRecords = acceptRecordService.findList(acceptRecordCriteria);
        if(acceptRecords.size()>0){
            throw new ServiceException(CommonCode.SERVER_INERNAL_ERROR,"该订单已进行入库！" );
        }
        if(!asnMaster.getWareCode().equals(updateSkuQuantity.getWareCode())){
            throw new ServiceException(CommonCode.SERVER_INERNAL_ERROR,"仓库编码异常："+asnMaster.getWareCode()+"||"+updateSkuQuantity.getWareCode());
        }
        for (Sku sku:skuList  ) {
            List<AsnDetail> list = asnDetailService.findByBillNo(updateSkuQuantity.getBillNo());
            for (AsnDetail asnDetail:list   ) {
                if(asnDetail.getItemCode().equals(sku.getSkuCode())){
                    asnDetail.setExpectQuantity(sku.getQuantity());
                    asnDetailService.updateById(asnDetail);
                }
            }
        }
        return ResultGenerator.genSuccessResult();
    }


    @ApiOperation(value = "ERP--》WMS推送入库异常解决方案", notes = "ERP--》WMS推送入库异常解决方案")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "access-token", value = "token", paramType = "header", dataType = "String", dataTypeClass = String.class,  required = true)
    })
    @PostMapping("/addInExResult")
    public Result addInExResult(@RequestBody InExResult inExResult, @ApiIgnore @User CurrentUser currentUser) {

        if(currentUser == null){
            return ResultGenerator.genFailResult(CommonCode.MISSING_PERMISSION_PARAMTER, null);
        }

        AcceptEx acceptEx = acceptExService.getById(Integer.parseInt( inExResult.getQcNo()));
        acceptEx.setFangan(inExResult.getExFangan());
        InExResult.ReturnInfo returnInfo = new InExResult.ReturnInfo();
        acceptEx.setReturnArea(returnInfo.getArea());
        acceptEx.setReturnCity(returnInfo.getCity());
        acceptEx.setReturnCountry(returnInfo.getCountry());
        acceptEx.setReturnDetailAddress(returnInfo.getDetailAddress());
        acceptEx.setReturnProvince(returnInfo.getProvince());
        acceptEx.setReturnLinkMan(returnInfo.getLinkMan());
        acceptEx.setReturnLinkPhone(returnInfo.getLinkPhone());
        acceptEx.setReturnExpressBillUrl(returnInfo.getExpressBillUrl());
        acceptEx.setReturnShipCode(returnInfo.getShipCode());
        acceptEx.setReturnShipBillCode(returnInfo.getShipBillCode());
        acceptEx.setState(2);
        acceptExService.updateById(acceptEx);
        return ResultGenerator.genSuccessResult();


    }


    @ApiOperation(value = "新增ASN信息", notes = "新增ASN信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "access-token", value = "token", paramType = "header", dataType = "String", dataTypeClass = String.class,  required = true)
    })
    @PostMapping("/insert")
    public Result add(@RequestBody AsnData asnData, @ApiIgnore @User CurrentUser currentUser) {
        if(currentUser == null){
            return ResultGenerator.genFailResult(CommonCode.MISSING_PERMISSION_PARAMTER, null);
        }
        if (ObjectUtil.isEmpty(asnData.getAsnMaster().getAsnType())) {
            throw new ServiceException(CommonCode.SERVER_INERNAL_ERROR,"请录入入库类别");
        }
        if (10==asnData.getAsnMaster().getAsnType()) {
            if (ObjectUtil.isEmpty(asnData.getAsnMaster().getSupplierId())) {
                throw new ServiceException(CommonCode.SERVER_INERNAL_ERROR,"请录入供应商");
            }
        }

        if (92==asnData.getAsnMaster().getAsnType()) {
            if (ObjectUtil.isEmpty(asnData.getAsnMaster().getCustomerId())) {
                throw new ServiceException(CommonCode.SERVER_INERNAL_ERROR,"请录入客户");
            }
        }
        asnMasterService.createAsnMaster(asnData,currentUser);
        return ResultGenerator.genSuccessResult();
    }


    @ApiOperation(value = "审核", notes = "审核")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "access-token", value = "token", paramType = "header", dataType = "String", dataTypeClass = String.class,  required = true)
    })
    @GetMapping("/review")
    public Result review(String billNo, Integer reviewResult,Integer caseDetailId,String memo, @ApiIgnore @User CurrentUser currentUser) {
        AsnMaster asnMaster = asnMasterService.findBy("bill_no", billNo);
        //-1不通过   0-流转中  1-通过  2-初始化
        Integer lastReviewResult = caseMasterService.review(caseDetailId,currentUser.getUserId(),reviewResult,memo);


        if (lastReviewResult == -1) {
            asnMaster.setState(-1);
            asnMasterService.updateById(asnMaster);
            BillRecord billRecord = billRecordService.findByBillNoAndType(billNo,3);//ASN审核
            billRecord.setResult("退回");
            billRecord.setModifyTime(DateUtils.getNowDateTimeString());
            billRecord.setModifyUserId(currentUser.getUserId());
            billRecord.setModifyUserName(currentUser.getUserName());
            billRecordService.updateById(billRecord);
        } else if (lastReviewResult == 0) {
            asnMaster.setState(0);
            asnMasterService.updateById(asnMaster);
            BillRecord billRecord = billRecordService.findByBillNoAndType(billNo,3);//ASN审核
            billRecord.setResult("流转");
            billRecordService.updateById(billRecord);
        }else if (lastReviewResult == 2) {
            asnMaster.setState(2);
            asnMasterService.updateById(asnMaster);
        } else if (lastReviewResult == 1) {
            asnMaster.setState(1);
            asnMasterService.updateById(asnMaster);
            BillRecord billRecord = billRecordService.findByBillNoAndType(billNo,3);//ASN审核
            billRecord.setResult("通过");
            billRecord.setModifyTime(DateUtils.getNowDateTimeString());
            billRecord.setModifyUserId(currentUser.getUserId());
            billRecord.setModifyUserName(currentUser.getUserName());
            billRecordService.updateById(billRecord);
        }
        return ResultGenerator.genSuccessResult();
    }


    @ApiOperation(value = "重新发起审核", notes = "重新发起审核")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "access-token", value = "token", paramType = "header", dataType = "String", dataTypeClass = String.class,  required = true)
    })
    @GetMapping("/reReview")
    public Result reReview(String billNo, @ApiIgnore @User CurrentUser currentUser) {
        if (currentUser == null) {
            return ResultGenerator.genFailResult(CommonCode.MISSING_PERMISSION_PARAMTER, null);
        }
        AsnMaster asnMaster = asnMasterService.findBy("bill_no", billNo);

        //初始化状态 2
        asnMaster.setState(2);
        asnMasterService.updateById(asnMaster);
        caseMasterService.createCase(billNo, 2, currentUser.getUserId(), asnMaster.getWareId(),asnMaster.getOrganizationId());

        return ResultGenerator.genSuccessResult();
    }


    @ApiOperation(value = "增删master、detail", notes = "增删master、detail")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "access-token", value = "token", paramType = "header", dataType = "String", dataTypeClass = String.class, required = true)
    })
    @PostMapping("/update")
    public Result update(@RequestBody AsnData asnData, @ApiIgnore @User CurrentUser currentUser) {
        if (currentUser == null) {
            return ResultGenerator.genFailResult(CommonCode.MISSING_PERMISSION_PARAMTER, null);
        }
        AsnMaster asnMaster = asnData.getAsnMaster();
        asnMasterService.updateById(asnMaster);

        List<AsnDetail> asnDetails = asnData.getAsnDetails();

        for (int i = 0; i < asnDetails.size(); i++) {
            AsnDetail asnDetail = asnDetails.get(i);
            String detailNo = asnData.getAsnMaster().getBillNo() + "-" + (i + 1);
            asnDetail.setDetailNo(detailNo);
            asnDetail.setBillNo(asnData.getAsnMaster().getBillNo());
            asnDetail.setDetailNo(detailNo);

            if (asnData.getInsertType() == -2) {
                asnDetail.setState(2);
            } else if (asnData.getInsertType() == 0) {
                asnDetail.setState(0);
            }
            asnDetailService.updateById(asnDetail);
        }
        return ResultGenerator.genSuccessResult();
    }

    @GetMapping("/detail")
    public Result detail(@PathVariable Integer id) {
        AsnMaster asnMaster = asnMasterService.getById(id);
        return ResultGenerator.genSuccessResult(asnMaster);
    }

    @GetMapping("/delete")
    public Result delete(Integer id) {
        asnMasterService.removeById(id);
        return ResultGenerator.genSuccessResult();
    }

    @ApiOperation(value = "入库任务关闭", notes = "关闭入库任务及入库任务明细")
    @GetMapping("/close")
    public Result close(Integer id) {
        asnMasterService.closeById(id);
        return ResultGenerator.genSuccessResult();
    }


    @GetMapping("/list")
    public Result list(AsnMasterCriteria criteria) {
        PageHelper.startPage(criteria.getPageNum(), criteria.getPageSize());
        List<AsnMasterDto> list = asnMasterService.findList(criteria);
        PageInfo pageInfo = new PageInfo(list);
        return ResultGenerator.genSuccessResult(pageInfo);
    }

    @GetMapping("/pdaList")
    public Result pdaList(AsnMasterCriteria criteria) {
       // PageHelper.startPage(criteria.getPageNum(), criteria.getPageSize());
        List<AsnMasterDto> list = asnMasterService.findPdaList(criteria);
       // PageInfo pageInfo = new PageInfo(list);
        return ResultGenerator.genSuccessResult(list);
    }

    @GetMapping("/qcList")
    public Result qcList(AsnMasterCriteria criteria) {
        PageHelper.startPage(criteria.getPageNum(), criteria.getPageSize());
        List<AsnMasterDto> list = asnMasterService.findQcList(criteria);
        PageInfo pageInfo = new PageInfo(list);
        return ResultGenerator.genSuccessResult(pageInfo);
    }

    @GetMapping("/findByBillNo")
    public Result findByBillNo(String billNo) {
        AsnMaster asnMaster = asnMasterService.getOneByField("bill_no", billNo);
        return ResultGenerator.genSuccessResult(asnMaster).setMessage("未查询到数据");
    }

    @ApiOperation(value = "归档ASN信息 传billNo", notes = "归档ASN信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "access-token", value = "token", paramType = "header", dataType = "String", dataTypeClass = String.class,  required = true)
    })
    @PostMapping("/file")
    public Result file(@RequestBody FileData fileData, @ApiIgnore @User CurrentUser currentUser) {
        if(currentUser == null){
            return ResultGenerator.genFailResult(CommonCode.MISSING_PERMISSION_PARAMTER, null);
        }
        for(int i=0;i<fileData.getBillNos().size();i++){
            String billNo = fileData.getBillNos().get(i);
            asnMasterService.createFile(billNo,currentUser);
        }

        return ResultGenerator.genSuccessResult();
    }

//    @ApiOperation(value = "ASN单据导入", notes = "ASN单据导入")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "access-token", value = "token", paramType = "header", dataType = "String", dataTypeClass = String.class,  required = true)
//    })
//    @Transactional
//    @PostMapping("/importAsnBills")
//    public Result importAsnBills(AsnImport excel, @ApiIgnore @User CurrentUser currentUser) {
//        if (currentUser == null) {
//            return ResultGenerator.genFailResult(CommonCode.MISSING_PERMISSION_PARAMTER);
//        }
//
//        jxl.Workbook billWorkbook = null;
//
//
//        String msg = "Excel 内容有问题，无法导入！";
//
//        try {
//            billWorkbook = jxl.Workbook.getWorkbook(excel.getModel().getInputStream());
//            jxl.Sheet billSheet = billWorkbook.getSheet(0);
//
//            int rows = billSheet.getRows();
//
//            AsnMaster asnMaster = new AsnMaster();
//
//            String tableName = "so_master";
//            //TODO:主键如何处理
////            Integer nextId = validatorService.getNextId(tableName);
////            asnMaster.setId(nextId);
//            asnMasterService.save(asnMaster);
//            String billNo ="ASN"+"-"+asnMaster.getId();
//
//
//            String wareName = ExcelUtils.getCellString(billSheet, 0, 2).trim();
//            Integer wareId = null;
//            WareInfo wareInfo = wareInfoService.getOneByField("ware_name", wareName);
//            if (wareInfo != null) {
//                wareId = wareInfo.getWareId();
//
//            } else {
//                msg = "仓库名称错误！" + wareName;
//                throw new Exception();
//            }
//
//            String organizationName = ExcelUtils.getCellString(billSheet, 1, 2).trim();
//            Integer organizationId = null;
//            Organization organization = organizationService.findBy("organization_name", organizationName);
//            if (organization != null) {
//                organizationId = organization.getOrganizationId();
//
//            } else {
//                msg = "货主名称错误！" + organizationName;
//                throw new Exception();
//            }
//            String supplierName = ExcelUtils.getCellString(billSheet, 2, 2).trim();
//            Integer supplierId = null;
//            SupplierManage supplierManage = supplierManageService.findBy("supplier_name", supplierName);
//            if (supplierManage != null) {
//                supplierId = supplierManage.getSupplierId();
//
//            } else {
//                msg = "供应商名称错误！" + supplierName;
//                throw new Exception();
//            }
//
//            String platformCode = ExcelUtils.getCellString(billSheet, 3, 2).trim();
//            String carrierName = ExcelUtils.getCellString(billSheet, 3, 2).trim();
//            String carrierCode = null;
//            Carrier carrier = carrierService.findBy("carrier_name", carrierName);
//            if (carrier != null) {
//                carrierCode = carrier.getCarrierCode();
//
//            } else {
//                msg = "承运方名称错误！" + organizationName;
//                throw new Exception();
//            }
//
//            String loadingPlace = ExcelUtils.getCellString(billSheet, 4, 2).trim();
//            String deliveryPlace = ExcelUtils.getCellString(billSheet, 4, 2).trim();
//            String trafficDescribe = ExcelUtils.getCellString(billSheet, 4, 2).trim();
//            String asnUdfHs1 = ExcelUtils.getCellString(billSheet, 4, 2).trim();
//            String asnUdfHs2 = ExcelUtils.getCellString(billSheet, 4, 2).trim();
//            String asnUdfHs3 = ExcelUtils.getCellString(billSheet, 4, 2).trim();
//            String expectTime = ExcelUtils.getCellString(billSheet, 4, 2).trim();
//
//            String createUserName = ExcelUtils.getCellString(billSheet, 3, 2).trim();
//            Integer userId = null;
//            QueryWrapper<UserInfo> wrapper=new QueryWrapper<>();
//            wrapper.eq("createUserName", createUserName);
//            UserInfo userInfo = userInfoService.getOne(wrapper);
//            if (userInfo != null) {
//                userId = userInfo.getUserId();
//            } else {
//                msg = "承运方名称错误！" + organizationName;
//                throw new Exception();
//            }
//
//            String memo = ExcelUtils.getCellString(billSheet, 9, 2);
//            asnMaster.setWareId(wareId);
//            asnMaster.setWareName(wareName);
//            asnMaster.setOrganizationId(organizationId);
//            asnMaster.setOrganizationName(organizationName);
//            asnMaster.setSupplierId(supplierId);
//            asnMaster.setSupplierName(supplierName);
//            asnMaster.setPlatformCode(platformCode);
//            asnMaster.setCarrierCode(carrierCode);
//            asnMaster.setLoadingPlace(loadingPlace);
//            asnMaster.setDeliveryPlace(deliveryPlace);
//            asnMaster.setTrafficDescribe(trafficDescribe);
//            asnMaster.setAsnUdfHs1(asnUdfHs1);
//            asnMaster.setAsnUdfHs2(asnUdfHs2);
//            asnMaster.setAsnUdfHs3(asnUdfHs3);
//            asnMaster.setState(0);
//            asnMaster.setCreateUserId(userId);
//            asnMaster.setCreateUserName(createUserName);
//            asnMaster.setOrderNo(1);
//            asnMaster.setExpectTime(expectTime);
//            asnMaster.setBillSource(4); //导入
//            asnMaster.setMemo(memo);
//
//            Integer state = caseMasterService.createCase(billNo, 2, currentUser.getUserId(), wareId,organizationId);
//
//            asnMaster.setState(state);
//
//
//            asnMasterService.updateById(asnMaster);
//
//
//            Integer rowCount = 0;
//            for (int i = 6; i < rows; i++) {
//                String content = ExcelUtils.getCellString(billSheet, 1, i);
//                if (content == null || "".equals(content)) {
//                    break;
//                }
//                rowCount++;
//            }
//
//            for (int i = 6; i < rowCount + 6; i++) {
//                String itemName = ExcelUtils.getCellString(billSheet, 0, i).trim();
//                if (itemName == null) {
//                    msg = "缺少物料名称！" + itemName;
//                    throw new Exception();
//                }
//
//                String packDescribe = ExcelUtils.getCellString(billSheet, 1, i);
//                if (packDescribe == null) {
//                    msg = "缺少单位！" + packDescribe;
//                    throw new Exception();
//                }
//
//                Double expectQuantity = ExcelUtils.getCellDouble(billSheet, 2, i);
//                if (expectQuantity == null) {
//                    msg = "缺少预期到货数量！" + expectQuantity;
//                    throw new Exception();
//                }
//
//                String memo1 = ExcelUtils.getCellString(billSheet, 3, i);
//                String asnUdfDs1 = ExcelUtils.getCellString(billSheet, 4, i);
//                String asnUdfDs2 = ExcelUtils.getCellString(billSheet, 5, i);
//                String asnUdfDs3 = ExcelUtils.getCellString(billSheet, 6, i);
//                ItemInfo itemInfo = itemInfoService.findBy("item_name",itemName);
//                PackDetail packDetail = packDetailService.findBy("pack_describe",packDescribe);
//
//                AsnDetail asnDetail = new AsnDetail();
//
//                asnDetail.setBillNo(billNo);
//                asnDetail.setDetailNo(billNo + "-" + (i-6+1));
//                asnDetail.setItemCode(itemInfo.getItemCode());
//                asnDetail.setItemName(itemName);
//                asnDetail.setPackDetailId(packDetail.getPackDetailId());
//                asnDetail.setPackDescribe(packDescribe);
//                asnDetail.setExpectQuantity(expectQuantity);
//                asnDetail.setMemo(memo1);
//                asnDetail.setAsnUdfDs1(asnUdfDs1);
//                asnDetail.setAsnUdfDs2(asnUdfDs2);
//                asnDetail.setAsnUdfDs3(asnUdfDs3);
//
//                asnDetailService.save(asnDetail);
//
//            }
//
//        } catch (Exception e) {
//            e.printStackTrace();
//            throw new ServiceException(CommonCode.WRONG_EXCEL_CONTENT, msg);
//
//        } finally {
//            billWorkbook.close();
//        }
//
//        return ResultGenerator.genSuccessResult();
//    }

    @ApiOperation(value = "单据导入", notes = "单据导入")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "access-token", value = "token", paramType = "header", dataType = "String", dataTypeClass = String.class, required = true)
    })
    @Transactional
    @PostMapping("/importAsnBills")
    public Result importAsnBills(AsnImport excel, @ApiIgnore @User CurrentUser currentUser) throws IOException {
        if (currentUser == null) {
            return ResultGenerator.genFailResult(CommonCode.MISSING_PERMISSION_PARAMTER);
        }
        if (excel.getModel() == null){
            throw new ServiceException(CommonCode.PARAMETERISNULL,"参数为空");
        }

        List<AsnExcelData> asnExcelDatas = ExcelUtil.readExcel(excel.getModel(), AsnExcelData.class, 0);
        //校验物料的种类是否小于明细的个数，如果小于表示有重复的物料
        Map<String, List<AsnExcelData>> collect = asnExcelDatas.stream().collect(Collectors.groupingBy(AsnExcelData::getItemCode));

        AsnMaster asnMaster = new AsnMaster();
        String tableName = "asn_master";
        Integer nextId = validatorService.getNextId(tableName);
        String billNo = "ZS"+"-"+nextId;
//        String billNo = codeRuleService.generateCodeByRedis(SystemManageConstant.CODE_RULE_SO);
        List<WareInfo> list = wareInfoService.list();
        asnMaster.setWareCode(list.get(0).getWareCode());
        asnMaster.setWareId(list.get(0).getWareId());
        asnMaster.setWareName(list.get(0).getWareName());
        asnMaster.setState(AsnManageConstant.ASN_STATE_INIT);
        asnMaster.setOrganizationId(-1);
        asnMaster.setOrganizationName("自有");
        asnMaster.setBillNo(billNo);
        asnMaster.setBillSource(3); //导入
        asnMaster.setCreateUserId(currentUser.getUserId());
        asnMaster.setCreateUserName(currentUser.getUserName());
//        asnMaster.setCreateTime(new Date());
        asnMaster.setMemo(asnExcelDatas.get(0).getRemark());
        asnMaster.setAsnType(ErpInConstant.ERP_IN_TYPE_ZS); //杂收
        asnMasterService.save(asnMaster);

        int count = 1;
        for (String itemStr : collect.keySet()) {
            AsnDetail asnDetail = new AsnDetail();
            asnDetail.setBillNo(billNo);
            asnDetail.setDetailNo(billNo + "-" + count);
            ItemInfo item = itemInfoService.getOneByField("item_code", itemStr);
            if (ObjectUtil.isNull(item)) {
                throw new ServiceException(CommonCode.SERVER_INERNAL_ERROR,"物料"+itemStr+"无法识别，请先同步物料数据");
            }
            asnDetail.setItemCode(item.getItemCode());
            asnDetail.setItemName(item.getItemName());
            asnDetail.setPackDetailId(167);
            asnDetail.setPackDescribe("PCS");
            List<AsnExcelData> dataList = collect.get(itemStr);
            double expectQty = 0.0;
            for (AsnExcelData asnExcelData : dataList) {
                expectQty += asnExcelData.getQuantity();
            }
            asnDetail.setExpectQuantity(expectQty);
            asnDetail.setTransRatio(1.0);

            asnDetailService.save(asnDetail);
            count++;
        }
        return ResultGenerator.genSuccessResult();
    }


    @GetMapping("/list2")
    public Result list2(AsnMasterCriteria criteria) {
        PageHelper.startPage(criteria.getPageNum(), criteria.getPageSize());
        List<AsnMasterDto> list = asnMasterService.findList2(criteria);
        PageInfo pageInfo = new PageInfo(list);
        return ResultGenerator.genSuccessResult(pageInfo);
    }

    @ApiOperation(value = "新增先发配件入库信息", notes = "新增先发配件入库信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "access-token", value = "token", paramType = "header", dataType = "String", dataTypeClass = String.class,  required = true)
    })
    @PostMapping("/insert2")
    public Result add2(@RequestBody AsnData asnData, @ApiIgnore @User CurrentUser currentUser) {
        if(currentUser == null){
            return ResultGenerator.genFailResult(CommonCode.MISSING_PERMISSION_PARAMTER, null);
        }
        asnMasterService.createAsnMaster2(asnData,currentUser);
        return ResultGenerator.genSuccessResult();
    }

    @GetMapping("savePurchaseOrder")
    public Result savePurchaseOrder(String date) {
        Map<String, Object> map = new HashMap<>();
        map.put("dateFrom", date);
        asnMasterService.savePurchaseOrder(map);
        return ResultGenerator.genSuccessResult();
    }

    /**
     * 产品入库--上架
     * */
    @ApiOperation(value = "WMS产品入库(数据回传ERP)", notes = "WMS产品入库(数据回传ERP)")
    @GetMapping("/toPutaway")
    public Result toPutaway(AsnMasterCriteria criteria,@ApiIgnore @User CurrentUser currentUser) {
        // 获取选中的入库任务
        // 解析前台
        List<Integer> idList=new ArrayList<>();
        String ids = criteria.getIds();
        if(ids!=null&&!ids.equals("")){
            // 按照逗号分隔成多个任务单号
            String[] list = ids.split(",");
            for(String id : list){
                idList.add(Integer.parseInt(id));
            }
        }
       List<AsnMaster> asnMasters=asnMasterService.listByIds(idList);
        // 每一条明细对应一个库存事务
       for(AsnMaster asnMaster:asnMasters){
             asnMasterService.accomplish(asnMaster, criteria.getCellCode(), currentUser);
            acceptRecordService.createByAsnDetail(asnMaster,criteria.getCellCode(),currentUser);
//            // 修改入库任务状态
//            asnMaster.setAsnState(3);
//            asnMasterService.updateById(asnMaster);
        }

        // 回传erp
//       for(AsnMaster asnMaster:asnMasters){
//            acceptRecordService.toERP(criteria.getCellCode(),asnMaster);
//       }
       return ResultGenerator.genSuccessResult();
    }


    @GetMapping("saveInTaskByERP")
    public Result saveInTaskByERP(@RequestBody Map<String,String> hashMap) {
        asnMasterService.saveInTaskByERP(hashMap);
        return ResultGenerator.genSuccessResult();
    }


    @ApiOperation(value = "ASN通知单查询接口", notes = "ASN通知单查询接口")
    @PostMapping("/addAsnNoticeOf")
    public Result addAsnNoticeOf(@RequestBody Map<String,String> hashMap){
        asnMasterService.addAsnNoticeOf(hashMap);
        return ResultGenerator.genSuccessResult();
    }

    @ApiOperation(value = "销售退货申请单查询接口", notes = "销售退货申请单查询接口")
    @PostMapping("/addSalesReturn")
    public Result addSalesReturn(@RequestBody Map<String,Object> hashMap){
        asnMasterService.addSalesReturn(hashMap);
        return ResultGenerator.genSuccessResult();
    }


    @ApiOperation(value = "生产退料申请单查询接口", notes = "生产退料申请单查询接口")
    @PostMapping("/addProductionMaterialReturn")
    public Result addProductionMaterialReturn(@RequestBody Map<String,Object> hashMap){
        asnMasterService.addProductionMaterialReturn(hashMap);
        return ResultGenerator.genSuccessResult();
    }

    @ApiOperation(value = "生产订单完工查询接口", notes = "生产订单完工查询接口")
    @PostMapping("/addCompletionProductionOrder")
    public Result addCompletionProductionOrder(@RequestBody Map<String,Object> hashMap){
        asnMasterService.addCompletionProductionOrder(hashMap);
        return ResultGenerator.genSuccessResult();
    }

    @ApiOperation(value = "委外退料查询接口", notes = "委外退料查询接口")
    @PostMapping("/getOutSourceBillNo")
    public Result getOutSourceBillNo(@RequestBody Map<String,Object> hashMap){
        asnMasterService.getOutSourceBillNo(hashMap);
        return ResultGenerator.genSuccessResult();
    }

    @ApiOperation(value = "委外收货查询接口", notes = "委外收货查询接口")
    @PostMapping("/queryOtherIn")
    public Result queryOtherIn(@RequestBody Map<String,Object> hashMap){
        asnMasterService.queryOtherIn(hashMap);
        return ResultGenerator.genSuccessResult();
    }

    @ApiOperation(value = "更新采购订单", notes = "")
    @GetMapping("/updateErp")
    @Transactional
    public Result updateErp(Integer id) {
        AsnMaster asnMaster = asnMasterService.getById(id);
        if (ObjectUtil.isNotNull(asnMaster)) {
            if (ObjectUtil.notEqual(0, asnMaster.getAsnState())) {
                throw new ServiceException(CommonCode.SERVER_INERNAL_ERROR, "任务不为新建状态，不允许更新");
            }
            //删除
            asnMasterService.updateErp(asnMaster);
        } else {
            throw new ServiceException(CommonCode.SERVER_INERNAL_ERROR, "未查询到任务");
        }

        return ResultGenerator.genSuccessResult();
    }


    @Transactional
    @ApiOperation(value = "回传ERP", notes = "回传ERP")
    @Authority
    @ApiImplicitParams({@ApiImplicitParam(name = "access-token", value = "token", paramType = "header", dataType = "String", dataTypeClass = String.class, required = true)})
    @PostMapping("/sendToErp")
    public Result sendToErp(@RequestBody Map<String,Object> hashMap, @ApiIgnore @User CurrentUser currentUser) {
        if (currentUser == null) {
            return ResultGenerator.genFailResult(CommonCode.MISSING_PERMISSION_PARAMTER, null);
        }
        Integer asnMasterId = (Integer) hashMap.get("asnMasterId");
        AsnMaster asnMaster = asnMasterService.getById(asnMasterId);
        if (ObjectUtil.isNotNull(asnMaster)) {
            UserInfo userInfo = userInfoService.getById(currentUser.getUserId());
            //不需要判断是否已经回传，ERP可以删除单子，传多了可以ERP删单
            this.sentToErpByInTask(asnMaster, userInfo.getJobNumber());
        } else {
            throw new ServiceException(CommonCode.SERVER_INERNAL_ERROR, "不存在入库任务，请确认");
        }

        return ResultGenerator.genSuccessResult();
    }

    @Transactional
    @ApiOperation(value = "退料回传ERP", notes = "回传ERP")
    @Authority
    @ApiImplicitParams({@ApiImplicitParam(name = "access-token", value = "token", paramType = "header", dataType = "String", dataTypeClass = String.class, required = true)})
    @PostMapping("/sendToErp2")
    public Result sendToErp2(@RequestBody Map<String, Object> hashMap, @ApiIgnore @User CurrentUser currentUser) {
         if (currentUser == null) {
            return ResultGenerator.genFailResult(CommonCode.MISSING_PERMISSION_PARAMTER, null);
        }
        Object requestObj = null;
        String requestUrl = "";

        try {
            String acceptIds = (String) hashMap.get("acceptIds");
            String[] split = acceptIds.split(",");

            List<AcceptRecord> acceptRecords = new ArrayList<>();
            for (String s : split) {
                AcceptRecord acceptRecord = acceptRecordService.getById(Integer.valueOf(s));
                acceptRecord.setErpState(1);
                acceptRecords.add(acceptRecord);
            }


//            Map<String, Double> result = acceptRecords.stream()
//                    .collect(Collectors.groupingBy(
//                            AcceptRecord::getItemCode, // 根据A字段分组
//                            Collectors.summingDouble(AcceptRecord::getQuantity) // 计算每组的数量
//                    ));
//
//            List<MiscellaneousVo> miscellaneousVos = new ArrayList<>();
//            MiscellaneousVo miscellaneousVo = new MiscellaneousVo();
//            miscellaneousVo.setDocType("MiscRcv001");
//            List<Lines> linesList = new ArrayList<>();
//            result.forEach((key, value) -> {
//                System.out.println("A字段值: " + key + ", 数量: " + value);
//                Lines lines = new Lines();
//                lines.setItemCode(key);
//                lines.setWhCode("ZP01"); //默认只会收入到于物料仓
//                lines.setStoreQty(value);//杂收数量
//                linesList.add(lines);
//                miscellaneousVo.setLines(linesList);
//            });
//
//            miscellaneousVos.add(miscellaneousVo);

            /**
             *
             * 退料 调拨接口
             * **/
//            Map<String, Double> result = acceptRecords.stream()
//                    .collect(Collectors.groupingBy(
//                            AcceptRecord::getItemCode, // 根据A字段分组
//                            Collectors.summingDouble(AcceptRecord::getQuantity) // 计算每组的数量
//                    ));
//
//            List<AllocatingOutboundVo> allocatingOutboundVoList = new ArrayList<>();
//            AllocatingOutboundVo allocatingOutboundVo = new AllocatingOutboundVo();
//            allocatingOutboundVo.setDocType("TransIn005");
//            List<LinesVo> linesVos = new ArrayList<>();
//            result.forEach((key, value) -> {
//                LinesVo linesVo = new LinesVo();
//                linesVo.setItemCode(key);
//                linesVo.setOutWhCode("WW01");//调出存储地点编码
//                linesVo.setInWhCode("ZP01");//调入存储地点编码(委外存储地点编码)
//                linesVo.setStoreQty(value);//杂收数量
//                linesVos.add(linesVo);
////                miscellaneousVo.setLines(linesList);
//            });
//            allocatingOutboundVo.setLines(linesVos);
//            allocatingOutboundVoList.add(allocatingOutboundVo);
//
//            requestObj = allocatingOutboundVoList;
//            requestUrl = ErpOutConstant.ERP_OUT_RETURL_OUTSOURCE;
////            requestUrl = ErpInConstant.ERP_IN_RETURL_ZS;
//            //回传erp
//            Map<String, Object> returnMap = new HashMap<>();
//            Map<String, Object> requestMap = new HashMap<>();
//
//            requestMap.put("data", requestObj);
//            requestMap.put("msg", "请求");
//            requestMap.put("code", 200);
////            erpRecordService.erpLog(requestMap, asnMaster.getAsnType());
//            returnMap = doPostOrGet(requestUrl, JSONObject.toJSONString(requestObj));
//            if (returnMap.get("code") == null || !"200".equals(returnMap.get("code").toString())) {
//                //报错记录
//                erpRecordService.erpLog(returnMap, 29999);
//                throw new ServiceException(CommonCode.SERVER_INERNAL_ERROR, "回传失败，具体原因：" + returnMap.get("msg").toString());
//            }
//            for (AcceptRecord acceptRecord : acceptRecords) {
//                acceptRecord.setErpState(1);
//            }
            acceptRecordService.saveOrUpdateBatch(acceptRecords);

        } catch (Exception e) {
            throw new ServiceException(CommonCode.SERVER_INERNAL_ERROR, e.getMessage());
//            erpRecordService.erpLog(returnMap, asnMaster.getAsnType());
        }

        return ResultGenerator.genSuccessResult();
    }

    @Autowired
    private ErpRecordService erpRecordService;

    private void sentToErpByInTask(AsnMaster asnMaster, String jobNumber) {
        Object requestObj = null;
        String requestUrl = "";

        if (ObjectUtil.equals(ErpInConstant.ERP_IN_TYPE_ZS, asnMaster.getAsnType())) {
//            List<AsnDetail> asnDetails = asnDetailService.getListByField("bill_no", asnMaster.getBillNo());
//            List<AsnDetail> collect = asnDetails.stream().filter(asnDetail -> asnDetail.getAcceptQuantity() > 0).collect(Collectors.toList());
            //用视图类
            List<AsnDetailView> asnDetails = asnDetailViewService.getListByField("bill_no", asnMaster.getBillNo());
            //筛选合格数量大于0
             List<AsnDetailView> collect =new ArrayList<>();
            for(AsnDetailView asnDetailView:asnDetails){
                if(ObjectUtil.isNotEmpty(asnDetailView.getQualifiedQuantity())) {
                    if (asnDetailView.getQualifiedQuantity() > 0) {
                        collect.add(asnDetailView);
                    }
                }
            }
            if (CollectionUtil.isEmpty(collect)) {
                throw new ServiceException(CommonCode.SERVER_INERNAL_ERROR, "没有可回传的数据!");
            }
            //杂收
            List<MiscellaneousVo> miscellaneousVos = new ArrayList<>();
            MiscellaneousVo miscellaneousVo = new MiscellaneousVo();
            miscellaneousVo.setDocType("MiscRcv001");
            List<Lines> linesList = new ArrayList<>();

            for (AsnDetailView asnDetail : collect) {
                Double acceptQty = asnDetail.getQualifiedQuantity();
                Lines lines = new Lines();
                lines.setItemCode(asnDetail.getItemCode());
                lines.setWhCode("ZP01"); //默认只会收入到于物料仓
                lines.setStoreQty(acceptQty);//杂收数量
                if (StringUtils.isNotEmpty(asnMaster.getSupplierCode())) {
                    lines.setSupplierCode(asnMaster.getSupplierCode());
                }
                linesList.add(lines);
                miscellaneousVo.setLines(linesList);
            }
            miscellaneousVos.add(miscellaneousVo);
            requestObj = miscellaneousVos;
            requestUrl = ErpInConstant.ERP_IN_RETURL_ZS;
        } else if (ObjectUtil.equals(ErpInConstant.ERP_IN_TYPE_ASN, asnMaster.getAsnType())) {
            //采购入库
            List<AcceptRecord> acceptRecords =
                    acceptRecordService.list(new QueryWrapper<AcceptRecord>().eq("asn_bill_no", asnMaster.getBillNo()).eq("erp_state", 0));
            if(CollectionUtil.isEmpty(acceptRecords)){
                throw new ServiceException(CommonCode.SERVER_INERNAL_ERROR, "没有可回传的数据!");
            }
            List<PurInBack> purInBacks = new ArrayList<>();
            PurInBack purInBack = new PurInBack(asnMaster);
            List<PurInDetailBack> purInDetailBacks = new ArrayList<>();
            for (AcceptRecord acceptRecord : acceptRecords) {
                AsnDetail asnDetail = asnDetailService.getOneByField("detail_no", acceptRecord.getAsnDetailNo());
//                PurInDetailBack purInDetailBack = new PurInDetailBack(asnDetail, acceptRecord.getQuantity());
                //这里传收货单合格数量
                PurInDetailBack purInDetailBack = new PurInDetailBack(asnDetail, acceptRecord.getQualifiedQuantity());
                purInDetailBack.setKgCode(jobNumber);
                purInDetailBack.setWhCode("ZP01"); //写死，只可能是物料仓
                purInDetailBacks.add(purInDetailBack);

                acceptRecord.setErpState(1);
            }
            purInBack.setRcvLineClasses(purInDetailBacks);
            purInBacks.add(purInBack);

            requestObj = purInBacks;
            requestUrl = ErpInConstant.ERP_IN_RETURL_ASN;

            acceptRecordService.updateBatchById(acceptRecords);
        }

        //回传erp
        Map<String, Object> returnMap = new HashMap<>();
        Map<String, Object> requestMap = new HashMap<>();
        try {
            requestMap.put("data", requestObj);
            requestMap.put("msg", "请求");
            requestMap.put("code", 200);
//            erpRecordService.erpLog(requestMap, asnMaster.getAsnType());
            returnMap = doPostOrGet(requestUrl, JSONObject.toJSONString(requestObj));
            if (returnMap.get("code") == null || !"200".equals(returnMap.get("code").toString())) {
                //报错记录
                erpRecordService.erpLog(returnMap, asnMaster.getAsnType());
                throw new ServiceException(CommonCode.SERVER_INERNAL_ERROR, "回传失败，具体原因：" + returnMap.get("msg").toString());
            }
        } finally {
//            erpRecordService.erpLog(returnMap, asnMaster.getAsnType());
        }
    }

    public static Map<String, Object> doPostOrGet(String pathUrl, String data) {
        System.out.println("=================================================");
        System.out.println(data);
        System.out.println("=================================================");
        OutputStreamWriter out = null;
        BufferedReader br = null;
        String result = "";
        Map<String, Object> map = new HashMap<>();
        try {
            URL url = new URL(pathUrl);
            //打开和url之间的连接
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            //请求方式
            conn.setRequestMethod("POST");
            //conn.setRequestMethod("GET");

            //设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
            conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
//            conn.setRequestProperty("Content-Type", "text/html;charset=utf-8");

            //DoOutput设置是否向httpUrlConnection输出，DoInput设置是否从httpUrlConnection读入，此外发送post请求必须设置这两个
            conn.setDoOutput(true);
            conn.setDoInput(true);

            /**
             * 下面的三句代码，就是调用第三方http接口
             */
            //获取URLConnection对象对应的输出流
            out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
            //发送请求参数即数据
            out.write(data);
            //flush输出流的缓冲
            out.flush();

            /**
             * 下面的代码相当于，获取调用第三方http接口后返回的结果
             */
            //获取URLConnection对象对应的输入流
            InputStream is = conn.getInputStream();
            //构造一个字符流缓存
            br = new BufferedReader(new InputStreamReader(is));
            String str = "";
            while ((str = br.readLine()) != null) {
                result += str;
            }
            map = JSON.parseObject(result);
            System.out.println(result);
            //关闭流
            is.close();
            //断开连接，disconnect是在底层tcp socket链接空闲时才切断，如果正在被其他线程使用就不切断。
            conn.disconnect();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (br != null) {
                    br.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return map;
    }
}
